package com.pay.paytoken.activity.lock;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.pay.paytoken.R;
import com.pay.paytoken.base.BaseActivity;
import com.pay.paytoken.patternLock.ViewAccessibilityCompat;
import com.pay.paytoken.paytoken.PayTokenConstant;

import java.util.List;

import appUtils.AppUtil;
import appUtils.LogUtil;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.OnClick;
import constant.AppConstants;
import weightUtils.PatternUtils;
import weightUtils.PatternView;

import static appUtils.SharedPreferencesManager.LOCK_GESTURE_PASS;
import static com.pay.paytoken.R.id.tv_pattern_title;
import static com.pay.paytoken.activity.lock.LockManager.CANBACK;
import static com.pay.paytoken.activity.lock.LockManager.TYPE;
import static com.pay.paytoken.paytoken.PayTokenConstant.ISLOCK;

/**
 * Created by Administrator on 2017/7/10.
 */

public class GestureLockActivity extends BaseActivity implements PatternView.OnPatternListener {
    private static final int CLEAR_PATTERN_DELAY_MILLI = 2000;
    private static final String KEY_NUM_FAILED_ATTEMPTS = "num_failed_attempts";
    private static final int ERROR_LIMIT_COUNT = 3;
    @Bind(tv_pattern_title)
    TextView mTitleView;
    @Bind(R.id.pl_pattern)
    PatternView mPatternView;
    private final Runnable mClearPatternRunnable = new Runnable() {
        public void run() {
            if (null != mPatternView) {
                mPatternView.clearPattern();
            }
        }
    };
    @Bind(R.id.activity_gesture_code_lock)
    TextView mCodeLockTv;
    //错误次数
    private int mErrorCount;
    private long mFirstTime = 0;
    //0为数字解锁 2为修改手势密码锁状态（开，关） 4为修改密码
    private int mType;
    private boolean mCanBack;

    @Override
    public int setView() {
        return R.layout.activity_lock_gesture;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mPatternView.setOnPatternListener(this);
        if (savedInstanceState == null) {
            mErrorCount = 0;
        } else {
            mErrorCount = savedInstanceState.getInt(KEY_NUM_FAILED_ATTEMPTS);
        }
        if (getIntent() != null) {
            mType = getIntent().getIntExtra(TYPE, 0);
            mCanBack = getIntent().getBooleanExtra(CANBACK, false);
        }
    }

    @Override
    public void initView() {
        if (mType == 2 || mType == 4) {
            mCodeLockTv.setVisibility(View.GONE);
        } else if (mType == 4) {
            mTitleView.setText(getString(R.string.please_enter_the_gesture_password_to_unlock));
        }
        if (mType == 2 || mType == 0) {
            mTitleView.setText(getString(R.string.please_to_gesture_to_unlock));
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mType == 2 || mType == 4) {
            ISLOCK = true;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        LogUtil.log("onSaveInstanceState");
        outState.putInt(KEY_NUM_FAILED_ATTEMPTS, mErrorCount);
    }

    @Override
    public void onPatternStart() {
        LogUtil.log("onPatternStart");
        removeClearPatternRunnable();
        // Set display mode to correct to ensure that pattern can be in stealth mode.
        mPatternView.setDisplayMode(PatternView.DisplayMode.Correct);
    }

    @Override
    public void onPatternCleared() {
        LogUtil.log("onPatternCleared");
        removeClearPatternRunnable();
    }

    @Override
    public void onPatternCellAdded(List<PatternView.Cell> pattern) {
        LogUtil.log("onPatternCellAdded");
    }

    @Override
    public void onPatternDetected(List<PatternView.Cell> pattern) {
        LogUtil.log("onPatternDetected");
        if (isPatternCorrect(pattern)) {
            setResult(RESULT_OK);
            finish();
        } else {
            if (onWrongPattern()) {
                mTitleView.setText(String.format(getString(R.string.gestures_error_you_can_also_enter_again_format), ERROR_LIMIT_COUNT - mErrorCount));
            }
            mPatternView.setDisplayMode(PatternView.DisplayMode.Wrong);
            postClearPatternRunnable();
            ViewAccessibilityCompat.announceForAccessibility(mTitleView, mTitleView.getText());
        }
    }

    @OnClick(R.id.activity_gesture_code_lock)
    public void onViewClicked() {
        LockManager.getInstance().startDigitalActivity(this, false);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mCanBack && (mType == 2 || mType == 4)) {
                return super.onKeyDown(keyCode, event);
            } else {
                if (System.currentTimeMillis() - mFirstTime > 2000) {
                    ToastUtil.showLong(R.string.again_according_to_exit_program);
                    mFirstTime = System.currentTimeMillis();
                } else {
                    AppConstants.isAppFinish = true;
                    AppUtil.getInstance().finishAllAC();
                    //killProcess
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    }, 500);
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    protected boolean onWrongPattern() {
        ++mErrorCount;
        if (mType != 2 && mType != 4) {
            if (mErrorCount == ERROR_LIMIT_COUNT) {
                LockManager.getInstance().startDigitalActivity(this, false);
                finish();
            }
            return true;
        }
        return false;
    }

    protected boolean isPatternCorrect(List<PatternView.Cell> pattern) {
        String patternSha1 = mSharedPreferencesManager.readString(LOCK_GESTURE_PASS, "");
        boolean isOk = TextUtils.equals(PatternUtils.patternToSha1String(pattern), patternSha1);
        if (isOk) {
            PayTokenConstant.isOK = true;
            if (mType == 2) {
                LockManager.getInstance().setGestureAble(false);
            }
            // the listener when pattern switch is open , need check pattern ,and pattern is true call start resetActivity
            if (mType == 4) {
                Intent intent = new Intent(this, GestureSetLockActivity.class);
                intent.putExtra(TYPE, 1);
                startActivity(intent);
            }
        }
        return isOk;
    }

    protected void removeClearPatternRunnable() {
        mPatternView.removeCallbacks(mClearPatternRunnable);
    }

    protected void postClearPatternRunnable() {
        removeClearPatternRunnable();
        mPatternView.postDelayed(mClearPatternRunnable, CLEAR_PATTERN_DELAY_MILLI);
    }
}
